<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/10/16 0016
 * Time: 13:30
 */

namespace Cuke\Services;


use Cuke\Http\PageResult;
use Cuke\Models\CukeGroup;

class GroupService extends ServiceBase
{

    /**
     * @var static
     */
    protected static $instance=null;
    /**
     * 获取分组详情
     * @param string $code
     * @param null|int $user_id
     * @return CukeGroup|\Phalcon\Mvc\Model\ResultInterface
     */
    public function getGroupDetailed($code,$user_id = null)
    {
        $sql = 'group_code=:group_code:';
        $params = ['group_code'=>$code];

        if(empty($user_id) === false){
            $sql .= ' AND user_id=:user_id:';
            $params['user_id'] = $user_id;
        }

        $group_detailed = CukeGroup::findFirst(['conditions' => $sql,'bind'=>$params]);


        return $group_detailed;
    }

    /**
     * 查询指定名称的分组是否存在
     * @param string $name
     * @param int $user_id
     * @param array|null $no_include_code
     * @return bool
     */
    public function existGroupByName($name,$user_id,$no_include_code = null)
    {
        $conditions =  'group_name=:group_name: AND user_id=:user_id:';
        $params = ['group_name'=>$name,'user_id'=>$user_id];

        if(empty($no_include_code) === false){
            $conditions  .= ' AND group_code NOT IN ({group_code:array})';
            $params['group_code'] = $no_include_code;
        }
        $group = CukeGroup::findFirst(['conditions' => $conditions,'bind' => $params]);

        return boolval($group);
    }

    /**
     * 分页查询分组信息
     * @param int $pageIndex
     * @param int $pageSize
     * @param null|int $user_id
     * @return PageResult
     */
    public function getGroupList($pageIndex = 1,$pageSize = 15,$user_id = null)
    {
        $conditions = 'group_id > 0';
        $params = [];
        if(empty($user_id) === false){
            $conditions .= ' AND user_id=:user_id:';
            $params['user_id'] = $user_id;
        }

        $offset = ($pageIndex - 1) * $pageSize;

        $list = CukeGroup::find([
            $conditions,
            'bind'       =>$params,
            'order'     => 'group_id DESC',
            'limit'      => $offset .','.$pageSize
        ]);
        $total_count = CukeGroup::count([ $conditions,'bind'=>$params]);
        return new PageResult($list,$total_count);
    }
}
